//c4
using System;

public class Node<T>
{
    public Node<T> Next { get; set; }
    public T Data { get; set; }

    public Node(T t)
    {
        Next = null;
        Data = t;
    }
}

public class GenericList<T>
{
    private Node<T> head;
    private Node<T> tail;

    public GenericList()
    {
        tail = head = null;
    }

    public Node<T> Head
    {
        get => head;
    }

    public void ForEach(Action<T> action)
    {
        Node<T> current = head;
        while (current != null)
        {
            action(current.Data);
            current = current.Next;
        }
    }

    public void Add(T item)
    {
        Node<T> newNode = new Node<T>(item);
        if (head == null)
        {
            head = tail = newNode;
        }
        else
        {
            tail.Next = newNode;
            tail = newNode;
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("泛型链表ForEach方法:");

        // 整型List
        Console.WriteLine("整型链表:");
        GenericList<int> intList = new GenericList<int>();
        for (int x = 1; x < 10; x++)
        {
            intList.Add(x);
        }

        Console.WriteLine("打印所有元素：");
        intList.ForEach(item => Console.Write($"{item} "));
        Console.WriteLine();

        int max = int.MinValue;
        intList.ForEach(item => {
            if (item > max) max = item;
        });
        Console.WriteLine($"最大值：{max}");

        int min = int.MaxValue;
        intList.ForEach(item => {
            if (item < min) min = item;
        });
        Console.WriteLine($"最小值：{min}");

        int sum = 0;
        intList.ForEach(item => sum += item);
        Console.WriteLine($"总和：{sum}");

        // 字符串List
        Console.WriteLine("字符串链表:");
        GenericList<string> strList = new GenericList<string>();
        for (int x = 1; x < 10; x++)
        {
            String str = new String('a', x);
            strList.Add(str);
        }

        Console.WriteLine("打印所有元素：");
        strList.ForEach(item => Console.Write($"{item} "));
        Console.WriteLine();

        string longest = "";
        strList.ForEach(item => {
            if (item.Length > longest.Length) longest = item;
        });
        Console.WriteLine($"最长的字符串：{longest}");

        string shortest = longest;
        strList.ForEach(item => {
            if (item.Length < shortest.Length) shortest = item;
        });
        Console.WriteLine($"最短的字符串：{shortest}");

        int strsum = 0;
        strList.ForEach(item => sum += item.Length);
        Console.WriteLine($"总和：{sum}");

    }
}